/**
 * 发送get异步请求
 * @param {stirng} url
 * @param {object} params
 * @param {function} callback
 * @param {object} headers
 */
function get(url, params, callback, headers = {}) {
  const xhr = new XMLHttpRequest();
  let temp = [];
  for (let key in params) {
    temp.push(`${key}=${params[key]}`);
  }
  xhr.open("get", `${url}?${temp.join(`&`)}`);
  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        let res = JSON.parse(xhr.responseText);
        callback(res);
      } else {
        console.log(`错误代码`, xhr.status);
      }
    }
  };
  for (let key in headers) {
    xhr.setRequestHeader(key, headers[key]);
  }
  xhr.send();
}

/**
 * 发送post异步请求
 * @param {stirng} url
 * @param {object} params
 * @param {function} callback
 * @param {object} headers
 */
function post(url, params, callback, headers = {}) {
  const xhr = new XMLHttpRequest();
  xhr.open("post", url);
  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        let res = JSON.parse(xhr.responseText);
        callback(res);
      } else {
        console.log(`错误代码`, xhr.status);
      }
    }
  };
  xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  for (let key in headers) {
    xhr.setRequestHeader(key, headers[key]);
  }
  let temp = [];
  for (let key in params) {
    temp.push(`${key}=${params[key]}`);
  }
  xhr.send(temp.join(`&`));
}
